package doublepointer;

import linkedlist.ListNode;

/**
 * @Classname : LinkedListCycleII
 * @Description : <a href="https://leetcode.cn/problems/linked-list-cycle-ii/">142. 环形链表 II</a>
 * @Author : chentianyu
 * @Date 2023/2/23 23:51
 */


public class LinkedListCycleII {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                fast = head;
                break;
            }
        }
        if (fast == null || fast.next == null) return null;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}
